package com.security.demo.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.security.demo.entity.User;
import com.security.demo.entity.UserRoleEnum;
import com.security.demo.repository.UserRepository;

public class CustomUserDetailsService implements UserDetailsService {

	@Autowired
	private UserRepository userRepository;
	
	private final static String rolePrefix = "ROLE_";

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User dbUser = userRepository.findByUsername(username);
		UserDetails userDetails = null;
		if (dbUser != null) {
			userDetails = new org.springframework.security.core.userdetails.User(dbUser.getUsername(),
					dbUser.getPassword().toLowerCase(), true, true, true, true, getAuthorities(dbUser.getRole()));
		} else {
			throw new UsernameNotFoundException("Error in retrieving user");
		}
		return userDetails;
	}

	/**
	 * 获得访问角色权限列表
	 * 
	 * @param access
	 * @return
	 */
	public Collection<SimpleGrantedAuthority> getAuthorities(Integer role) {
		List<SimpleGrantedAuthority> authList = new ArrayList<SimpleGrantedAuthority>();
		UserRoleEnum userRole = UserRoleEnum.getByValue(role);
		if(userRole!=null){
			authList.add(new SimpleGrantedAuthority(rolePrefix+userRole.name()));
		}
		return authList;
	}

}
